﻿var view;//二维地图视图
var map;//二维地图对象
var map3d;//三维地图对象
var mapScene;//三维场景对象
var mapCamera; //三维相机对象
var _mapAttr; //初始化视图配置对象 
_mapAttr = {
    map_Projection: m_baseParameter["map_Projection"],
    map_Center: [m_baseParameter["map_CenterCoordinate_x"], m_baseParameter["map_CenterCoordinate_y"]],
    map_InitialZoom: m_baseParameter["map_InitialZoom"],
    map_MinZoom: m_baseParameter["map_MinZoom"],
    map_MaxZoom: m_baseParameter["map_MaxZoom"],
    map_Resetlevel: m_baseParameter["map_Resetlevel"],
    viewModel: {
        hueShift: m_baseParameter["map_hueShift"],
        saturationShift: m_baseParameter["map_saturationShift"],
        brightnessShift: m_baseParameter["map_brightnessShift"],
        lightingFadeOutDistance: m_baseParameter["map_lightingFadeOutDistance"],
        lightingFadeInDistance: m_baseParameter["map_lightingFadeInDistance"]
    },
    initalViewModel: {
        lon: m_baseParameter["map_lon"],
        lat: m_baseParameter["map_lat"],
        height: m_baseParameter["map_height"],
        heading: m_baseParameter["map_heading"],
        tilt: m_baseParameter["map_tilt"],
        roll: m_baseParameter["map_roll"],
        duration: m_baseParameter["map_duration"]
    },
    baseLayer: {
        imgLayer:[
        ],
        vectorLayer:[
        ]
    },
    baseMapLayerGroup:m_baseMapLayerGroup
};
view = new ol.View({
    projection: ol.proj.get(_mapAttr.map_Projection),
    center: _mapAttr.map_Center,
    zoom: _mapAttr.map_InitialZoom,
    minZoom: _mapAttr.map_MinZoom,
    maxZoom: _mapAttr.map_MaxZoom
    //resolutions: resolutions
});
var thisBaseLayers = InitalBaseMapLayer(m_baseParameter, m_baseMapLayerGroup, m_baseMapGroup_Layer, m_baseMapLayer);
map = new ol.Map({

    //禁止双击放大地图
    interactions: ol.interaction.defaults({
        doubleClickZoom: false
    }),

    //使用默认的 controls ，但是把默认的「版权控件」设置为false，隐藏掉了
    controls: ol.control.defaults({
        attribution: false,
        rotate: false,
        zoom: false
    }),

    target: 'OLCesiumMap', //地图容器div的ID
    loadTilesWhileAnimating: true,
    //地图容器中加载的图层
    layers: thisBaseLayers,
    view: view //地图视图设置

});


map3d = new olcs.OLCesium({ map: map });
mapScene = map3d.getCesiumScene();
//mapScene._creditContainer.style.display = "none";
//mapScene.globe.depthTestAgainstTerrain = true;//面贴地
//map3d.setEnabled(false);//控制二维三维显示
var selectInteraction = null;
$(document).ready(function () {
    ////设置显示为2D
    //map3d.setEnabled(false);
    //禁止右键默认事件
    $("#OLCesiumMap").bind("contextmenu", function (e) {
        return false;
    });

    //添加选择交互工具
    var selectInteractionStyle = new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(255, 0, 0, 1)',
            width: 3
        }),
        fill: new ol.style.Fill({
            color: 'rgba(255, 0, 0, 0.8)'
        }),
        image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({
                color: 'rgba(255, 0, 0, 1)'
            })
        })
    });
    var lastSelectInfo = null;
    selectInteraction = new ol.interaction.Select({
        condition: ol.events.condition.singleClick,     // 单击获取要素
        layers: function (layer) {
            switch (layer.values_.name) {
                case "locationLayer":
                case "viewResultLayer":
                    return true;
                    break;
                default:
                    return false;
                    break;
            }
        },
        style: selectInteractionStyle
    });
    selectInteraction.set("name", "selectInteraction");
    map.addInteraction(selectInteraction);
    selectInteraction.on("select", function (e) {
        var options = {
            pixel: e.mapBrowserEvent.pixel
        }
        var rightMenu = new MouseRightMenu(options);
        features = e.selected;
        if (features.length > 0) {
            if (lastSelectInfo!=null) {
                lastSelectInfo[0].setStyle(lastSelectInfo[1]);
                lastSelectInfo = null;
            }
            lastSelectInfo = [features[0], features[0].style_];
            features[0].setStyle(selectInteractionStyle);

            rightMenu.create(function (result) {
                if (result=="copy") {
                    mouseRight_copyResult = features;
                    alert("复制成功");
                    other_copyHeightLight();
                    selectInteraction.getFeatures().clear();
                }
                else if (result=="paste") {
                    alert("该功能正在开发中");
                }
                else if (result=="property") {
                    var property = features[0].values_.propinfo;
                    if (property) {
                        property = JSON.parse(property);
                        showFeatureProperty(property);
                        console.log(property);
                    }
                    else {
                        alert("该要素暂无属性");
                    }
                }
            });
        }
        else {
            rightMenu.close();
            if (lastSelectInfo!=null) {
                lastSelectInfo[0].setStyle(lastSelectInfo[1]);
                lastSelectInfo = null;
            }
        }
    });
});

mapCamera = map3d.getCamera();
//mapCamera.cam_.flyTo({
//    destination: Cesium.Cartesian3.fromDegrees(_mapAttr.initalViewModel.lon, _mapAttr.initalViewModel.lat, _mapAttr.initalViewModel.height),
//    duration: _mapAttr.initalViewModel.duration,
//    orientation: {
//        heading: Cesium.Math.toRadians(_mapAttr.initalViewModel.heading),
//        pitch: Cesium.Math.toRadians(_mapAttr.initalViewModel.tilt),
//        roll: Cesium.Math.toRadians(_mapAttr.initalViewModel.roll)
//    }
//});
//var skyAtmosphere = mapScene.skyAtmosphere;
//var globe = mapScene.globe;
//var skyNameList = ["hueShift", "saturationShift", "brightnessShift"];
//var globeNameList = ["atmosphereHueShift", "atmosphereSaturationShift", "atmosphereBrightnessShift"];
//for (var i = 0; i < skyNameList.length; i++) {
//    skyAtmosphere[skyNameList[i]] = _mapAttr.viewModel[skyNameList[i]];
//    globe[globeNameList[i]] = _mapAttr.viewModel[globeNameList[i]];
//}

//地形初始化
if (false) {//map3d
    var terrLayerInfo = {
        GUID:"base_terrain",
        URL: m_baseParameter["W3D_BaseTerrain_url"],
        NAME:"基础地形服务",
        SERVICETYPE:"terrain",
        TOKEN:m_baseParameter["W3D_BaseTerrain_token"]
    };
    var terrainService = new TerrainService(terrLayerInfo);
    var terrianLayer = terrainService.CreateLayer();
    if (terrianLayer != null) {
        mapScene.terrainProvider = terrianLayer;
    }  
}
//初始化底图加载
function InitalBaseMapLayer(mapBaseParameter,MapBaseLayerGroup, MapBaseGroupLayer, MapBaseLayer, mapGridlevel) {
    var VisibleGroupName = "";
    var mapProjection = mapBaseParameter["map_Projection"]; //坐标系
    var mapMaxZoom = parseInt(mapBaseParameter["map_MaxZoom"]); //最大比例尺级别
    var mapGridlevel = parseInt(mapBaseParameter["map_Gridlevel"]); //切片级别
    for (var obj in MapBaseLayerGroup) {
        var layergroupVisible = MapBaseLayerGroup[obj]["visible"];
        var layergroupName = MapBaseLayerGroup[obj]["name"];
        if (layergroupVisible == "true") {
            VisibleGroupName = layergroupName;
            break;
        }
    }
    var gridNames = [];
    var gridNames_c = [];
    
    var projExtent = ol.proj.get(mapProjection).getExtent();
    var startResolution = ol.extent.getWidth(projExtent) / 256;
    var resolutions = new Array(mapMaxZoom);
    for (i = 1; i < mapGridlevel; i++) {
        gridNames[i] = mapProjection + ":" + i;
        gridNames_c[i]=i;
        resolutions[i] = startResolution / Math.pow(2, i);
    }
    //for (var i = 0, ii = resolutions.length; i < ii; ++i) {
     //   resolutions[i] = startResolution / Math.pow(2, i);
    //}
    var tileGrid1 = new ol.tilegrid.WMTS({
        origin: ol.extent.getTopLeft(projExtent),
        resolutions: resolutions,
        tileSize: [256, 256],
        matrixIds: gridNames_c
    });
    var thisLayer = [];
    var n = 0;
    for (var i = 0; i < MapBaseGroupLayer[VisibleGroupName].length; i++) {
        var layername = MapBaseGroupLayer[VisibleGroupName][i];
        var baseLayerInfo = MapBaseLayer[layername];
        var layerHelp = new LayerHelper(baseLayerInfo);
        var myLayer = layerHelp.GetLayer();
        myLayer.getSource().set("type", "baseLayer", true);
        thisLayer[n] = myLayer;
        n++;
    }

    return thisLayer;
}